﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Reflection;
using MITI;
using System.Data.SqlServerCe;

namespace WBrowser.MY_CODE
{
    public partial class ReadTemplateFiles : Form
    {
        private string[] _filePaths;
        private DataSet _dataSet;
        private DataView _dataView;
        private List<string> _forumType;

        public ReadTemplateFiles()
        {
            InitializeComponent();
            BaseDBCe.g_ConnectStr = GeneralClass.ConnectString();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            _forumType = new List<string>();
            _filePaths = Directory.GetFiles(textBoxURL.Text, "*.mpb", SearchOption.AllDirectories);
            _dataSet = CreateDataSetForumList(_filePaths);
            //Add dropdownlist
            dropDownListForumType.DataSource = _forumType;

            //Add gridview
            _dataView = _dataSet.Tables[0].DefaultView;
            gridViewForums.DataSource = _dataView;
            gridViewForums.Columns[0].Frozen = true;
            gridViewForums.Columns[1].Frozen = true;
            gridViewForums.Columns[2].Frozen = true;
        }

        private void ReadTemplateFiles_Load(object sender, EventArgs e)
        {
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            textBoxURL.Text = Path.GetDirectoryName(currentAssembly.Location) + @"\Templates\";
        }

        public DataSet CreateDataSetForumList(string[] _filePaths)
        {
            XmlDocument doc;
            XmlNode node;
            XmlNodeList nodeList;

            DataSet ds = new DataSet();
            DataTable db = new DataTable("Forums");
            DataRow dr;

            int columnNum;
            //Init forum type
            _forumType.Clear();
            _forumType.Add("");

            for (int i = 0; i < _filePaths.Length; i++)
            {
                doc = new XmlDocument();
                doc.Load(_filePaths[i]);
                node = doc.DocumentElement;
                nodeList = node.ChildNodes;

                //just add columnNum columns
                //columnNum = 6;
                columnNum = nodeList.Count;

                //Create datatable
                if (db.Columns.Count == 0)
                {
                    db = new DataTable();
                    for (int j = 0; j < columnNum; j++) //just add columnNum columns
                    {
                        db.Columns.Add(nodeList[j].Name);

                    }
                }

                //Add data in table
                dr = db.NewRow();
                for (int j = 0; j < columnNum; j++) //just add columnNum columns
                {
                    //Add forum type
                    if (nodeList[j].Name == "Type" && !_forumType.Contains(nodeList[j].InnerText))
                        _forumType.Add(nodeList[j].InnerText);

                    //Add data in table
                    dr[nodeList[j].Name] = nodeList[j].InnerText;
                }
                db.Rows.Add(dr);
            }

            //Add datatable in dataset
            ds.Tables.Add(db);
            return ds;
        }

        private void dropDownListForumType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_dataView != null)
            {
                _dataView.RowFilter = "Type = '" + dropDownListForumType.Text + "'";
                gridViewForums.DataSource = _dataView;
            }
        }

        /// <summary>
        /// Add data in Thread table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            DataSet dsData = BaseDBCe.ExecSql_DataSet("select * from Templates where forum_name = 'vBulletin-bestsoft.zapto.org'");
            //dsData.Tables[0].Columns.Remove("username");
            //dsData.Tables[0].Columns.Remove("password");
            //dsData.Tables[0].Columns.Remove("group");
            
            DataSet dsFile = _dataSet.Copy();
            //dsFile.Tables[0].Columns.Remove("Encoding");
            //dsFile.Tables[0].Columns.Remove("Notes");
            //dsFile.Tables[0].Columns.Remove("TemplateVersion");
            SqlCeResultSet rs = BaseDBCe.ExecSql_GetTable("Threads");
            SqlCeUpdatableRecord rc;
            for (int i = 0; i < dsFile.Tables[0].Columns.Count; i++)
            {
                rc = rs.CreateRecord();
                rc.SetString(0, dsData.Tables[0].Columns[i].ColumnName);
                rc.SetString(1, dsFile.Tables[0].Columns[i].ColumnName);
                rs.Insert(rc);
            }
            MessageBox.Show("Successful!");
        }

        private void btnAddTemplates_Click(object sender, EventArgs e)
        {
            DataSet dsThreads = BaseDBCe.ExecSql_DataSet("select * from Threads");
            DataSet dsTemplates = BaseDBCe.ExecSql_DataSet("select * from Templates");
            List<string> forumNames = new List<string>();
            foreach (DataRow dr in dsTemplates.Tables[0].Rows)
            {
                forumNames.Add(dr["forum_name"].ToString().Trim());
            }

            SqlCeResultSet rs = BaseDBCe.ExecSql_GetTable("Templates");
            SqlCeUpdatableRecord rc;

            foreach (DataRow dr in _dataSet.Tables[0].Rows)
            {
                //Kiểm tra xem url này đã có trong template chưa
                var result = from x in forumNames
                             where x.ToLower().Trim() == dr["ForumName"].ToString().ToLower().Trim()
                             select x;
                //Nếu không tìm thấy thì thêm vào
                if (result.Count() == 0)
                {
                    rc = rs.CreateRecord();
                    //init values for every column in a row
                    for (int i = 0; i < dsThreads.Tables[0].Rows.Count; i++)
                    {
                        if (dsThreads.Tables[0].Rows[i][1].ToString() == string.Empty)
                        {
                            if (dsThreads.Tables[0].Rows[i][0].ToString() == "username")
                                rc.SetString(i, "mrforumvn");
                            else if (dsThreads.Tables[0].Rows[i][0].ToString() == "password")
                                rc.SetString(i, "gmail.com489183");
                            else if (dsThreads.Tables[0].Rows[i][0].ToString() == "group")
                                rc.SetString(i, "10");
                        }
                        else
                            rc.SetString(i, dr[dsThreads.Tables[0].Rows[i][1].ToString()].ToString());
                    }
                    rs.Insert(rc);

                    //Add into list
                    forumNames.Add(dr["ForumName"].ToString().Trim());
                }
                
                
            }
            MessageBox.Show("Successful!");

        }

        /// <summary>
        /// Update table
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            DataSet dsData = BaseDBCe.ExecSql_DataSet("select * from Templates where forum_name = 'vBulletin-bestsoft.zapto.org'");
            //dsData.Tables[0].Columns.Remove("username");
            //dsData.Tables[0].Columns.Remove("password");
            //dsData.Tables[0].Columns.Remove("group");

            DataSet dsFile = _dataSet.Copy();
            //dsFile.Tables[0].Columns.Remove("Encoding");
            //dsFile.Tables[0].Columns.Remove("Notes");
            //dsFile.Tables[0].Columns.Remove("TemplateVersion");
            SqlCeResultSet rs = BaseDBCe.ExecSql_GetTable("Threads");
            for (int i = 17; i < dsData.Tables[0].Columns.Count; i++)
            {
                // Update the ith record
                //
                if (true == rs.ReadAbsolute(i))
                {
                    //rs.SetString(0, dsData.Tables[0].Columns[i].ColumnName);
                    rs.SetString(1, dsFile.Tables[0].Columns[i-2].ColumnName);
                    rs.Update();
                }
            }
            MessageBox.Show("Successful!");
        }
    }
}
